﻿namespace Services.Implement;

public class SystemConfigBLL(ISqlSugarClient db) : BaseBLL<SystemConfig>(db), ISystemConfigBLL
{
    private readonly ISqlSugarClient _db = db;
    /// <summary>
    /// 获取全部系统设置
    /// </summary>
    /// <returns></returns>
    public async Task<List<SystemConfig>> GetAllAsync()
    {
        return await _db.Queryable<SystemConfig>().ToListAsync();
    }

    /// <summary>
    /// 保存系统设置
    /// </summary>
    /// <param name="configList"></param>
    /// <returns></returns>
    public async Task<ResultModel> SaveAsync(List<SaveSystemConfigRM> configList)
    {
        ResultModel resultModel = new ResultModel();
        var allList = await GetAllAsync();
        var addList = new List<SystemConfig>();
        var updateList = new List<SystemConfig>();
        foreach (var config in configList)
        {
            var exist = await GetAsync(x => x.Id == config.Id);
            if (exist != null)
            {
                exist.Value = config.ConfigValue;
                updateList.Add(exist);
            }
            else
            {
                addList.Add(new SystemConfig
                {
                    Key = config.ConfigCode,
                    Value = config.ConfigValue,
                    Remark = config.Mark,
                });
            }
        }
        if (addList.Count != 0)
        {
            resultModel.data = await InsertAsync(addList);
        }

        if (updateList.Count != 0)
        {
            resultModel.data = await UpdateAsync(updateList);
        }
        resultModel.code = 1;
        return resultModel;
    }
}
